require(['../config/requireconfig'],function(config){
	//根据需要添加
	require(['zepto', 'common/mcommon', 'common/prodFeedBack', 'common/validate'],function($,com,feedBack){
		com.init();
		feedBack.init();
		var pageLogic = new PageLogic($,com);
		pageLogic.init();
		$(".page-loading-info").addClass("with-txt");
	});
});
var PageLogic = function($,com){
	return{
		init:function(){
			var _this = this;
			_this.prdTypeIniterGenor =  _this.prdTypeIniter();
			$("#subForm").validate(function(res){
				if(!res.success){
					com.toast("您的数据提交失败");
				}else{
					com.toast("您的数据提交成功",function(){
						window.location.reload();
					});
				}
			},{
				validate:function(){
					return true;
				}});
			_this.bindEvent();
		},
		bindEvent:function(){
			var _this = this;
			$("#notice").on("click",function(){
				if($(this).hasClass("active")){
					$(this).removeClass("active");
				}else{
					$(this).addClass("active");
				}
			});
			$("#ico-camera").on("click",function(){
				$(".inp-img").click();
			});
			$(".inp-img").on("change",function(){
				var fileContent = $('#inpFile')[0].files[0];
				if(fileContent){

					$(".page-loading-info").addClass("with-txt");
					$(".page-loading-info-con").find(".info").text("压缩图片中");
					$(".page-loading").show().addClass("loading");
					commonPhotoCompress($('#inpFile')[0].files[0],700,function(result){
						var formData = new FormData();
						formData.append("file",convertBase64UrlToBlob(result));
						com.ajax({
							url:"/alivinAnalyze.json",
							data:formData,
							type:"post",
							isMultiPart:true,
							loadingtext:"读取图片信息中..",
							success:function (res) {
								if(!res.success){
									com.toast("图像解析失败");
								}else{
									$("#inpVin").val(res.data.data);
								}
							}
						});
					});
				}
			});
			$("#btnSerch").on("click",function(){
				var inpVal = $("#inpVin").val();
				inpVal = $.trim(inpVal);
				if(!inpVal || inpVal && inpVal.length !=17 ){
					com.toast("请输入17位VIN码");
					return;
				}
				com.ajax({
					url:"/searchProdByVin.json",
					data:{vin:inpVal},
					loadingtext:"vin信息查询中",
					success:function(res){
						if(res.success && res.data && res.data.carInfo){
							$(".res").removeClass("fail");
							$(".res").addClass("suc");
							$("#carInfo").html(_this.prdDetailInfo(res.data.carInfo));
							_this.genSucBlock(res.data);
						}else{
							// $("#feed").click();
							$(".res").removeClass("suc");
							// _this.resetFailBlock();
							$(".res").addClass("fail");
						}
					}
				});
			});
			$(".types").find("li").find(".item-top").on("click",function(){
				var tg = $(this).attr("tg");
				if(tg == "lt"){
					var url = "partLtCar.htm";
					url += "?vehicleNo=" + $(this).attr("par");
					com.utils().windowJump(url);
					return;
				}
				if($(this).hasClass("active")){
					$(this).removeClass("active");
				}else{
					$(this).addClass("active");
				}
			});
			$(".item-sub").on("click",function(){
				var url = "partsQuery2.htm";
				url += "?vehicleNo=" + $(this).attr("par");
				url += "&sublineNo=" + $(this).attr("tg");
				com.utils().windowJump(url);
			});
		},
		compressFiles:function(formData,file,doback){
			var configW = 600;
			var quality = 1;
			if(file){
				var URL = window.URL || window.webkitURL;
				var blob = URL.createObjectURL(file);
				var img = new Image();
				img.src =blob;
				img.onload = function() {
					var that = this;

					//生成比例
					var w = that.width,
						h = that.height,
						scale = w / h;
					w = configW || w;
					h = w / scale;

					//生成canvas
					var canvas = document.createElement('canvas');
					var ctx = canvas.getContext('2d');
					$(canvas).attr({
						width: w,
						height: h
					});
					ctx.drawImage(that, 0, 0, w, h);
					/**
					 * 生成base64
					 * 兼容修复移动设备需要引入mobileBUGFix.js
					 */
					var base64 = canvas.toDataURL('image/jpeg', quality || 0.8);

					// 修复IOS
					if (navigator.userAgent.match(/iphone/i)) {
						var mpImg = new MegaPixImage(img);
						mpImg.render(canvas, {
							maxWidth: w,
							maxHeight: h,
							quality: quality || 0.8
						});
						base64 = canvas.toDataURL('image/jpeg', quality || 0.8);
					}

					// 修复android
					if (navigator.userAgent.match(/Android/i)) {
						var encoder = new JPEGEncoder();
						base64 = encoder.encode(ctx.getImageData(0, 0, w, h), quality * 100 || 80);
					}
					formData.append("file",convertBase64UrlToBlob(base64));
					doback.call(null,formData);
				}
			}
		},
		contentAnalyze:function(obj){
			var _this = this;
			if(obj.current){
				var reg =  /[\u4e00-\u9fa5]/g;
				obj.current = obj.current.replace(reg,"");
			}
			if(obj.current.length > obj.maxCode.length){
				obj.maxCode = obj.current;
			}
			return obj;
		},
		genSucBlock:function(res){
			var AbleProd = res.AbleProd;
			var AbleProdSGMD = res.AbleProdSGMD;
			var tyrelst = res.tyreList;
			var prdType = res.vechileNo;
			this.prdTypeIniterGenor.init(AbleProd,AbleProdSGMD,tyrelst,prdType);
		},
		resetFailBlock:function(){
			$("#brandNm").val("");
			$("#carAndVol").val("");
			$("#generationAndType").val("");
			$("#remark").val("");
		},
		prdDetailInfo:function(res){
			var html = "";
			html += '<table class="prd-detail"> ';
			html += '    <tr class="prd-header"> ';
			html += '        <td> ';
			html += '            品牌 ';
			html += '        </td> ';
			html += '        <td> ';
			html += '            车系 ';
			html += '        </td> ';
			html += '        <td> ';
			html += '            车型 ';
			html += '        </td> ';
			html += '        <td> ';
			html += '            排量 ';
			html += '        </td> ';
			html += '    </tr> ';
			$(res).each(function(){
				html += '    <tr class="row" tg="' + this.LevelID + '"> ';
				html += '        <td> ';
				html += this.BRAND_NAME;
				html += '        </td> ';
				html += '        <td> ';
				html += (this.MODEL_NAME?this.MODEL_NAME:"");
				html += '        </td> ';
				html += '        <td> ';
				html += (this.ENGINE_NO?this.ENGINE_NO:"");
				html += '        </td> ';
				html += '        <td> ';
				html += (this.DISPLACEMENT_L?this.DISPLACEMENT_L:"");
				html += '        </td> ';
				html += '    </tr> ';
			});
			html += '</table> ';
			return html;
		},
		prdTypeIniter:function(){
			return {
				init:function(AbleProd,AbleProdSGMD,tyrelst,prdType){
					var _this = this;
					_this.options = [];
					_this.lis = [];
					_this.prdType = prdType;
					_this.doByAbleProd(AbleProd);
					_this.doByTyreLst(tyrelst);
					_this.doByBasicType(AbleProdSGMD);
					_this.genTypes();
					_this.bindEvents();
				},
				doByAbleProd:function(AbleProd){
					var _this = this;
					if(AbleProd && AbleProd.length > 0){
						$(AbleProd).each(function(){
							var objType  = this;
							var tmpType;
							if(_this.options){
								$(_this.options).each(function(idx,type){
									if(type.keytype == objType.ktype){
										tmpType = objType;
									}
								});
							}
							if(!tmpType){
								_this.options.push({keytype:objType.ktype,name:objType.modelName});
								_this.lis.push({keytype:objType.ktype,name:objType.modelName,subs:[]});
							}
						});

						$(AbleProd).each(function(){
							var objType = this;
							$(_this.lis).each(function(idx,obj){
								if(objType.ktype == obj.keytype){
									obj.subs.push(objType);
								}
							});
						});
					}
				},
				doByTyreLst:function(tyrelst){
					var _this = this;
					if(tyrelst && tyrelst.length > 0){
						_this.options.push({keytype:"lt",name:"轮胎"});
						_this.lis.push({keytype:"lt",name:"轮胎"});
					}
				},
				doByBasicType:function(AbleProdSGMD){
					var _this = this;
					_this.options.push({keytype:"hxp",name:"油液及化学品"});
					var subArr = [];
					if(AbleProdSGMD && AbleProdSGMD.length > 0){
						$(AbleProdSGMD).each(function(){
							if(this.valveNum == "10H"){
								subArr.push({valveNum:"10H",modelNo:"自动变速箱油"});
							}else if(this.valveNum == "10D"){
								subArr.push({valveNum:"10D",modelNo:"汽机油"});
							}

						});
						subArr.push({valveNum:"10C",modelNo:"防冻液"});
						subArr.push({valveNum:"10E",modelNo:"制动液"});
						subArr.push({valveNum:"10F",modelNo:"转向助力液"});
						subArr.push({valveNum:"10B",modelNo:"齿轮油"});
						subArr.push({valveNum:"10J",modelNo:"冷媒"});
					}else{
						subArr.push({valveNum:"10C",modelNo:"防冻液"});
						subArr.push({valveNum:"10D",modelNo:"汽机油"});
						subArr.push({valveNum:"10E",modelNo:"制动液"});
						subArr.push({valveNum:"10F",modelNo:"转向助力液"});
						subArr.push({valveNum:"10H",modelNo:"自动变速箱油"});
						subArr.push({valveNum:"10B",modelNo:"齿轮油"});
						subArr.push({valveNum:"10J",modelNo:"冷媒"});
					}
					_this.lis.push({keytype:"hxp",name:"油液及化学品",subs:subArr});
				},
				genTypes:function(){
					var _this = this;

					var html = "";
					$(_this.lis).each(function(){
						var subIco = '';
						if(this.subs && this.subs.length >0){
							subIco = '<i class="icon"></i> ';
						}
						html += '<li class="item" tg="' + this.keytype + '"> ';
						html += '	<div class="item-top"  par="' + _this.prdType + '" tg="' + this.keytype + '" > ';
						html += '		' + this.name + subIco;
						html += '	</div> ';
						if(this.subs && this.subs.length >0){
							html += '	<ul class="item-subs"> ';
							$(this.subs).each(function(idx,obj){
								html += '<li class="item-sub" par="' + _this.prdType + '" tg="' + obj.valveNum + '"><span>';
								html += obj.modelNo
								html += '</span></li> ';
							});
							html += '	</ul> ';
						}

						html += '</li> ';
					});
					$(".types").html(html);
				},
				bindEvents:function(){

					$(".types").find("li").find(".item-top").on("click",function(){
						var tg = $(this).attr("tg");
						if(tg == "lt"){
							var url = "partLtCar.htm";
							url += "?vehicleNo=" + $(this).attr("par");
							com.utils().windowJump(url);
							return;
						}
						if($(this).hasClass("active")){
							$(this).removeClass("active");
						}else{
							$(this).addClass("active");
						}
					});
					$(".item-sub").on("click",function(){
						var url = "partsQuery2.htm";
						url += "?vehicleNo=" + $(this).attr("par");
						url += "&sublineNo=" + $(this).attr("tg");
						com.utils().windowJump(url);
					});
				}
			}
		}
	}
}

function commonPhotoCompress(file, w, objDiv) {
	var ready = new FileReader();
	/*
	 * 开始读取指定的Blob对象或File对象中的内容.
	 * 当读取操作完成时,readyState属性的值会成为DONE,如果设置了onloadend事件处理程序,则调用之.同时,result属性中将包含一个data:
	 * URL格式的字符串以表示所读取文件的内容.
	 */
	ready.readAsDataURL(file);
	ready.onload = function() {
		var re = this.result;
		commonCanvasDataURL(re, w, objDiv)
	}
}
function commonCanvasDataURL(re, w, objDiv) {
	var newImg = new Image();
	newImg.src = re;
	var imgWidth, imgHeight, offsetX = 0, offsetY = 0;
	newImg.onload = function() {
		var img = document.createElement("img");
		img.src = newImg.src;
		imgWidth = img.width;
		imgHeight = img.height;
		var canvas = document.createElement("canvas");
		canvas.width = w;
		canvas.height =  w * imgHeight / imgWidth;
		var ctx = canvas.getContext("2d");
		ctx.clearRect(0, 0, w, w);
		if (imgWidth > imgHeight) {
			imgWidth = w * imgWidth / imgHeight;
			imgHeight = w;
			offsetX = -Math.round((imgWidth - w) / 2);
		} else {
			imgHeight = w * imgHeight / imgWidth;
			imgWidth = w;
			offsetY = -Math.round((imgHeight - w) / 2);
		}
		ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
		var base64 = canvas.toDataURL("image/jpeg", 0.7);
		if (typeof objDiv == "object") {
			objDiv.appendChild(canvas);
		} else if (typeof objDiv == "function") {
			objDiv(base64);
		}
	}
}

function convertBase64UrlToBlob(urlData){
	var bytes=window.atob(urlData.split(',')[1]);        //去掉url的头，并转换为byte

	//处理异常,将ascii码小于0的转换为大于0
	var ab = new ArrayBuffer(bytes.length);
	var ia = new Uint8Array(ab);
	for (var i = 0; i < bytes.length; i++) {
		ia[i] = bytes.charCodeAt(i);
	}
	return new Blob( [ab] , {type : 'image/png'});
}